<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域-->
    <el-card>
      <el-row :gutter="0">
        <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      </el-row>

      <!--角色列表区域-->
      <el-table :data="roleList" border stripe>
        <!--展开列-->
        <el-table-column type="expand" label="详情">
          <template v-slot="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.RoleRightId)">{{item1.name}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级三级权限-->
              <el-col :span="19">
                <!--通过for循环嵌套渲染二级权限-->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.RoleRightId)">{{item2.name}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.RoleRightId)">{{item3.name}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px;">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="removeRole(scope.row.id)" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 5, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

    </el-card>
    <!--添加角色的对话框-->
    <el-dialog title="添加角色"
               :visible.sync="addDialogVisible"
               width="50%" @close="addDialogClosed">
      <!--内容主体区-->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="role1">
          <el-input v-model="addForm.role1"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="content">
          <el-input v-model="addForm.content"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改用户的对话框-->
    <el-dialog title="修改角色"
               :visible.sync="aditDialogVisible"
               width="50%" @close="aditDialogClosed">
      <!--内容主体区-->
      <el-form ref="aditFormRef" :model="aditForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="role1">
          <el-input v-model="aditForm.role1"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="content">
          <el-input v-model="aditForm.content"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="aditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="aditRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配权限的对话框-->
    <el-dialog title="分配权限"
               :visible.sync="setRightDialogVisible"
               width="50%" @close="setRightDialogClosed">
      <!--树形控件-->
      <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

  export default {
    data() {
      return {
        // 获取角色列表的参数对象
        queryInfo: {
          pagenum: 1,
          pagesize: 5
        },
        total: 0,
        // 所有角色列表数据
        roleList: [],
        // 添加角色表单数据
        addForm: {
          role1: '',
          content: ''
        },
        addDialogVisible: false,
        // 添加用户表单的验证规则对象
        addFormRules: {
          role1: [
            { required: true, message: '请输入的角色名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '请输入的角色描述', trigger: 'blur' }
          ]
        },
        // 控制修改用户对话框的显示与隐藏
        aditDialogVisible: false,
        // 查询到的用户信息
        aditForm: {},
        // 控制分配权限对话框的显示与隐藏
        setRightDialogVisible: false,
        // 所有权限数据
        rightslist: [],
        // 树形控件的属性绑定
        treeProps: {
          label: 'name',
          children: 'children'
        },
        // 默认选中的节点id值数组
        defKeys: [],
        // 当前即将分配权限的id
        roleId: ''
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      // 获取所有角色数据列表
      async getRolesList() {
        const { data: res } = await this.$http.get('GetRoles', { params: this.queryInfo })
        if (!res.state) {
          return this.$message.error(res.text)
        }
        console.log(res)
        this.roleList = res.data.data
        this.total = res.data.total
      },
      // 监听pagesize改变的事件
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getRolesList()
      },
      // 监听页码值 改变的事件
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getRolesList()
      },
      // 删除角色权限
      async removeRightById(role, id) {
        await this.$confirm('此操作将删除该角色的权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$http.post('DeleteRolesRightById', { id })
          if (!res.state) {
            return this.$message.error(res.text)
          }
          if (res.data.length === 0) {
            role.children = res.data
          } else {
            role.children = res.data[0].children
          }
          this.$message.success(res.text)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 监听关闭添加用户对话框的关闭事件
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      // 点击按钮添加新用户
      addRoles() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return false
          const { data: res } = await this.$http.post('AddRoles', this.addForm)
          if (!res.state) {
            return this.$message.error(res.text)
          }
          this.$message.success(res.text)
          this.addDialogVisible = false
          this.getRolesList()
        })
      },
      // 修改用户信息对话框
      async showEditDialog(id) {
        const { data: res } = await this.$http.get('GetRolesInfo?id=' + id)
        if (!res.state) {
          return this.$message.error(res.text)
        }
        this.aditForm = res.data
        console.log(this.aditForm)
        this.aditDialogVisible = true
      },
      // 监听关闭修改用户对话框的关闭事件
      aditDialogClosed() {
        this.$refs.aditFormRef.resetFields()
      },
      // 修改用户信息
      async aditRoles() {
        this.$refs.aditFormRef.validate(async valid => {
          if (!valid) return false
          const { data: res } = await this.$http.post('UpdateRoles', this.aditForm)
          if (!res.state) {
            return this.$message.error(res.text)
          }
          this.$message.success(res.text)
          this.aditDialogVisible = false
          this.getRolesList()
        })
      },
      // 删除角色信息以及权限
      async removeRole(id) {
        await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$http.post('DeleteRoles', { id })
          if (!res.state) {
            return this.$message.error(res.text)
          }
          this.$message.success(res.text)
          this.getRolesList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 展示分配权限的对话框
      async showSetRightDialog(role) {
        this.roleId = role.id
        const { data: res } = await this.$http.get('GetMenuTree')
        if (!res.state) {
          return this.$message.error(res.text)
        }
        // 把获取到的权限数据保存到data中
        this.rightslist = res.data
        this.getLeafKeys(role, this.defKeys)
        this.setRightDialogVisible = true
      },
      // 获取三级权限id
      getLeafKeys(node, arr) {
        if (node.children.length === 0) {
          return arr.push(node.id)
        }

        node.children.forEach(item => this.getLeafKeys(item, arr))
      },
      // 监听关闭分配权限对话框的关闭事件
      setRightDialogClosed() {
        this.defKeys = []
      },
      // 为角色分配权限
      async allotRights() {
        const keys = [
          ...this.$refs.treeRef.getHalfCheckedKeys(),
          ...this.$refs.treeRef.getCheckedKeys()
        ]
        // const idStr = keys.join(',')
        const { data: res } = await this.$http.post('UpdateRoleRights', { rolesID: this.roleId, rids: keys })
        if (!res.state) {
          return this.$message.error(res.text)
        }
        this.$message.success(res.text)
        this.getRolesList()
        this.setRightDialogVisible = false
      }
    }
}
</script>

<style lang="less" scoped>
  .el-tag{
    margin:7px;
  }
  .bdtop{
    border-top:1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display:flex;
    align-items:center;
  }
</style>
